package com.dingwen.treasure.business.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.dingwen.treasure.base.controller.BaseViewController;
import com.dingwen.treasure.common.redis.service.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 　RedisLockController
 * 　@author dingwen
 * 　@date 2022/5/13$
 */
@Api(tags = "基于redis实现分布式锁")
@RestController
@RequestMapping("redis/lock")
@Slf4j
public class RedisLockController implements BaseViewController {
    /**
     * common key
     */
    public static String REDIS_KEY_LOCK_PREFIX = "redis:common:lock:";

    /**
     * test key
     */
    public static String KEY_TEST = "test";

    /**
     * redis 服务
     */
    @Resource
    private RedisService redisService;

    /**
     * redis lock 实现测试 </br>
     * <p>存在问题，过期事件设置多少合适，能否确保key能够正确删除不导致死锁问题，后期使用redisson实现</p>
     *
     * @return Result
     */
    @GetMapping
    @ApiOperation("redis lock 实现测试")
    public void test() {
        boolean ifAbsent = redisService.setIfAbsent(REDIS_KEY_LOCK_PREFIX.concat(KEY_TEST), "lock test", 1L, TimeUnit.MINUTES);
        // 剩余时间
        long expire = redisService.getExpire(REDIS_KEY_LOCK_PREFIX.concat(KEY_TEST), TimeUnit.SECONDS);
        String message = StrUtil.format("频繁的操作，请{}秒后重试", expire);

        // key被锁定时返回提示信息
        Assert.isTrue(ObjectUtil.isNotNull(ifAbsent) && ifAbsent, message);

    }

}
